# 初始化y1和y2的数组
y_values = []

for i, det in enumerate(pred):
    seen += 1
    if webcam:
        p, im0, frame = path[i], im0s[i].copy(), dataset.count
        s += f'{i}: '
    else:
        p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

    p = Path(p)  # to Path
    save_path = str(save_dir / p.name)  # im.jpg
    txt_path = str(save_dir / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt

    '''
    ================================================================================================
    '''
    with open(f'{txt_path}.txt', 'a') as f:
        pass
    file_path_left = save_dir / 'left' / f'{p.stem}.txt'

    # 获取文件夹路径
    folder_path_left = os.path.dirname(file_path_left)

    # 检查文件夹是否存在，如果不存在，则创建
    if not os.path.exists(folder_path_left):
        os.makedirs(folder_path_left)

    # 如果文件不存在，则创建空文件
    if not os.path.exists(file_path_left):
        open(file_path_left, 'a').close()

    with open(file_path_left, 'a', encoding='utf-8') as file:
        pass
    '''
    ================================================================================================
    '''

    csv_path = str(save_dir / 'results')
    column_path = str(save_dir / 'column')
    img_name = str(p.stem)
    s += '%gx%g ' % im.shape[2:]  # print string
    gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
    imc = im0.copy() if save_crop else im0  # for save_crop
    annotator = Annotator(im0, line_width=line_thickness, example=str(names))

    if len(det):
        # 在处理每一帧开始时，重置names_dic
        for key, value in names.items():
            names_dic[value] = 0

        # Rescale boxes from img_size to im0 size
        det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()

        # Print results
        for c in det[:, 5].unique():
            n = (det[:, 5] == c).sum()  # detections per class
            s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

        # 检测到物体了，画框.如果没检测到物体不会执行循环
        count = 1
        # file_path = save_dir / 'left' / f'{p.stem}.txt'
        fp = '2.txt'
        # with open(file_path, 'w') as file:
        #     file.truncate(0)  # 清除1.txt文档内容

        with open(fp, 'w') as file:
            file.truncate(0)  # 清除2.txt文档内容

        with open(f'{csv_path}.csv', 'a', newline='') as csv_file:
            # 定义CSV写入器
            writer = csv.DictWriter(csv_file, fieldnames=["序号ID", "文件路径", "目标类别",
                                                          "坐标位置",
                                                          "评判可信度", "目标面积",
                                                          "目标占比", "检测时间"])

            # 写入表头
            writer.writeheader()

        for *xyxy, conf, cls in reversed(det):
            if save_txt:  # Write to file
                xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(
                    -1).tolist()  # normalized xywh

                line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format

                # 根目录下txt文档记录位置信息等
                x1 = int(xyxy[0])
                y1 = int(xyxy[1])
                x2 = int(xyxy[2])
                y2 = int(xyxy[3])

                y_values.append(y1)
                y_values.append(y2)

                x_1 = xywh[0]
                y_1 = xywh[1]
                w_1 = xywh[2]
                h_1 = xywh[3]

                ww = x2 - x1  # 宽度
                hh = y2 - y1  # 高度
                ss = ww * hh  # 面积

                xx = ww / w_1  # 图片宽度
                yy = hh / h_1  # 图片高度
                SS = xx * yy  # 图片面积
                # print(SS)

                zb = ss / SS  # 占比
                xyxy1 = [int(num) for num in xyxy]
                xyxy1 = str(xyxy1).replace(" ", "")

                # xx1 = x1 - 0.1 * ww
                # yy1 = 0
                # xx2 = x2 + 0.1 * ww
                # yy2 = hh
                # xyxy2 = [xx1, yy1, xx2, yy2]

                current_time = datetime.datetime.now()
                formatted_time = current_time.strftime("%Y-%m-%d-%H:%M:%S")

                with open(f'{txt_path}.txt', 'a') as f:
                    f.write(
                        f"{count} {img_path} {names[int(cls)]} {conf * 100:.2f}% "
                        f"{xyxy1} {ss} {zb * 100:.2f}% {formatted_time}\n")

                global number
                with open(f'{column_path}.txt', 'a') as column:
                    column.write(
                        f"{number} {img_path} {names[int(cls)]} {conf * 100:.2f}% "
                        f"{xyxy1} {ss} {zb * 100:.2f}% {formatted_time}\n")
                    number += 1

                # 要保存的数据列表
                data1 = [
                    {
                        "序号ID": count,
                        "文件路径": img_path,
                        "目标类别": names[int(cls)],
                        "坐标位置": [f'%.2f' % num for num in xyxy],
                        "评判可信度": f'{conf * 100:.2f}%',
                        "目标面积": ss,
                        "目标占比": f'{zb * 100:.2f}%',
                        "检测时间": formatted_time
                    }
                ]
                # 打开CSV文件并写入数据
                with open(f'{csv_path}.csv', 'a', newline='') as csv_file:
                    # 定义CSV写入器
                    writer = csv.DictWriter(csv_file, fieldnames=["序号ID", "文件路径", "目标类别",
                                                                  "坐标位置",
                                                                  "评判可信度", "目标面积",
                                                                  "目标占比", "检测时间"])

                    # 写入表头
                    # writer.writeheader()

                    # 循环写入数据
                    for row in data1:
                        writer.writerow(row)

                file_path = save_dir / 'left' / f'{p.stem}.txt'

                # 获取文件夹路径
                folder_path = os.path.dirname(file_path)

                # 检查文件夹是否存在，如果不存在，则创建
                if not os.path.exists(folder_path):
                    os.makedirs(folder_path)

                # 如果文件不存在，则创建空文件
                if not os.path.exists(file_path):
                    open(file_path, 'a').close()

                with open(file_path, 'a', encoding='utf-8') as file:
                    # 写入文字到文件中
                    file.write(
                        f"{count} {img_name} {names[int(cls)]} {x1} {y1} {x2} {y2} "
                        f"{ww} {hh} {ss} {zb * 100:.2f}% {conf * 100:.2f}%\n")

                with open(fp, 'a', encoding='utf-8') as file:
                    # 写入文字到文件中
                    file.write(
                        f"{count} {img_path} {names[int(cls)]} {conf * 100:.2f}% "
                        f"{xyxy1} {ss} {zb * 100:.2f}% {formatted_time}\n")

                    # 序号 文件名称 缺陷类别，X最小值  Y最小值 X最大值 Y最大值
                    # 缺陷宽度 缺陷高度 缺陷面积 缺陷占比 评判可信度

                count += 1

            if save_img or save_crop or view_img:  # Add bbox to image
                c = int(cls)  # integer class
                label = f'{names[c]} {conf:.2f}'
                annotator.box_label(xyxy, label, color=colors(c, True))

                # names_dic列表中 对应类别名字 数量+1
                if names[c] in names_dic:
                    names_dic[names[c]] += 1

            # 保存框选图片
            if save_crop:
                save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

            # 如果检测到ERROR目标 保存
            if names[c] == "ERROR":
                xx1 = x1 - 0.05 * xx
                yy1 = 0
                xx2 = x2 + 0.05 * xx
                yy2 = yy
                xyxy2 = [xx1, yy1, xx2, yy2]
                error_dir = os.path.join(save_dir, 'IQI')
                os.makedirs(error_dir, exist_ok=True)
                txt_file_path = os.path.join(error_dir, f'{p.stem}.txt')
                with open(txt_file_path, 'w') as f:
                    f.write(f"{str(xx1)} {str(xx2)}")
                save_one_box(xyxy2, imc, file=save_dir /'IQI'/ f'{p.stem}.jpg', BGR=True)

    # Stream results
    im0 = annotator.result()
    self.send_img.emit(im0)

    # 发送names_dic
    self.send_detectinfo_dic.emit(names_dic)

    # 发送检测速度
    self.detect_speed.emit(str(round(t[0], 1)))

    if view_img:
        cv2.imshow(str(p), im0)
        cv2.waitKey(1)  # 1 millisecond

    if save_img:
        if dataset.mode == 'image':
            cv2.imwrite(save_path, im0)
        else:  # 'video' or 'stream'
            if vid_path[i] != save_path:  # new video
                vid_path[i] = save_path
                if isinstance(vid_writer[i], cv2.VideoWriter):
                    vid_writer[i].release()  # release previous video writer
                if vid_cap:  # video
                    fps = vid_cap.get(cv2.CAP_PROP_FPS)
                    w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                    h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                else:  # stream
                    fps, w, h = 30, im0.shape[1], im0.shape[0]
                save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
                vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
            vid_writer[i].write(im0)

# 在循环结束后处理y_values
yy_half = yy / 2
greater_than_half = [y for y in y_values if y > yy_half]
less_than_half = [y for y in y_values if y < yy_half]

min_max = min(greater_than_half) if greater_than_half else None
max_min = max(less_than_half) if less_than_half else None

# 将min_max和max_min保存在文档里面
result_file_path = save_dir / 'results' / 'y_values.txt'
with open(result_file_path, 'w') as result_file:
    result_file.write(f"min_max: {min_max}\n")
    result_file.write(f"max_min: {max_min}\n")
